package com.cropdoctor.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Component
public class Img2Base64 {
    //将图片转换为base64
    public static String jpgToBase(String pathName) throws IOException {
        //使用spring boot自带的ResourceUtils从资源路径中获取文件
        File file = ResourceUtils.getFile(pathName);
        FileInputStream fileInputStream = new FileInputStream(file);
        //使用IO流将其转换为字节数组
        byte[] bytes = IOUtils.toByteArray(fileInputStream);
        //将字节转换为base64
        String encodeBase64 = Base64.encodeBase64String(bytes);
        //关闭IO流
        fileInputStream.close();
        return encodeBase64;
    }
}
